<?php
/**
 * Introduction: 会员操作业务逻辑
 * @author: 杨陈鹏
 * @date: 2016/4/05 16:04
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Common\Logic;

use Common\Model;

class MemberLogic
{
    static public $model,$apply_dis,$income;

    public function __construct()
    {

        self::$model = new Model\MemberModel();

        self::$apply_dis = new Model\ApplyDistributionModel();

        self::$income   =   new Model\MemberIncomeRecordModel();

    }

    /**
     * @introduction: 获取数据
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $where 查询条件
     * @param string $limit 分页
     * @param string $fileds 需要获取的字段
     * @return array
     */
    static public function getData($where = '', $limit = '0,20', $fields = '*', $order = 'create_time desc')
    {

        $data = self::$model
            ->where($where)
            ->order($order)
            ->limit($limit)
            ->field($fields)
            ->select();

        $total = self::$model
            ->where($where)
            ->count();

        return ['data' => $data, 'total' => $total];

    }

    /**
     * @introduction: 获取一条数据
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param array or string $where 查询条件
     * @param $fileds 需要获取的字段
     * @return array
     */
    static public function getOneData($where = '', $fileds = '*')
    {

        return self::$model
            ->where($where)
            ->field($fileds)
            ->find();

    }

    /**
     * @introduction: 插入数据
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 需要插入的数据
     * @return array
     */
    static public function create($data)
    {

        //获取第三方登录open_id
        $open_id = $data['open_id'];

        //检测是否是第三方注册
        if ($open_id) {

            return self::thirdRegister($data);

        }


        //检测用户名是否存在和用户名合法性

        if($data['username']){
            $check = self::checkUsername($data['username']);
            if ($check['code'] == 300)
                return $check;
        }

        //验证密码合法性
        //if(!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/",$data['password']))
        if (!preg_match("/^[0-9A-Za-z]{5,}$/", $data['password']))
            return ['code' => 300, 'msg' => '密码格式不对!'];

        //检测手机号码是否存在和手机号码合法性
        $check = self::checkMobile($data['mobile']);
        if ($check['code'] == 300)
            return $check;

        //检测手机验证码
        if (session('mobile_code_' . $data['mobile']) != $data['mobile_code'])
            return ['code' => 300, 'msg' => '短信验证码错误!'];

        unset($data['mobile_code']);

        //获取邀请码
        $invitation = $data['invitation'];
        unset($data['invitation']);

        //密码加密
        $passwdInfo = password($data['password']);

        $data['username'] = strtolower($data['username']);

        $data['password'] = $passwdInfo['password'];

        $data['encrypt'] = $passwdInfo['encrypt'];

        $data['nicname'] = $data['nicname'] ? $data['nicname'] : $data['username'];

        $data['create_ip'] = get_client_ip();

        $data['is_edit'] = 1;

        $data['create_time'] = NOW_TIME;

        //生成邀请码
        $data['invitation'] = strtolower(create_randomstr(8));

        //检测邀请码是否已存在
        if (self::$model->where(['invitation' => $data['invitation']])->find())
            $data['invitation'] = create_randomstr(8);

        $data['uuid'] = md5(md5($data['create_time']) . $data['invitation']);

        if ($uid = self::$model->add($data)) {

            //如果有邀请码则梳理子父级关系
            if ($invitation)
                self::invitation($invitation, $uid);

            //返回用户数据
            $userinfo = self::$model
                ->where(['uid' => $uid])
                ->field('uuid,username,nicname,mobile,avatar,create_time,autograph,invitation')
                ->find();

            $userinfo['create_time'] = date('Y-m-d H:i:s',$userinfo['create_time']);


            return ['code' => 200, 'msg' => '注册成功!', 'data' => $userinfo];

        }

        return ['code' => 300, 'msg' => '注册失败!'];

    }

    /**
     * @introduction: 第三方快捷注册
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 手机号码
     * @return array
     */
    private function thirdRegister($data)
    {

        if (!$data['open_id'])
            return ['code' => 300, 'msg' => '参数错误,open_id为空'];

        if (!$data['source_type'])
            return ['code' => 300, 'msg' => '参数错误,source_type为空'];

        $invitation = $data['invitation'];

        //检测手机号码
        $check = self::checkMobile($data['mobile']);
        if ($check['code'] == 300)
            return $check;

        //检测手机验证码
        //设置超级验证码   微信端跨域用  零时用
        //if ($data['mobile_code'] != 9999) {

            if (session('mobile_code_' . $data['mobile']) != $data['mobile_code'])
                return ['code' => 300, 'msg' => '短信验证码错误!'];

       // }


        //系统生成数据
        //密码加密
        $passInfo = password($data['password']);


        $data['password'] = $passInfo['password'];

        $data['encrypt'] = $passInfo['encrypt'];


        if($data['username']){

            $data['username'] = strtolower($data['username']);



        }
        if($data['nicname']){


            $data['nicname'] = $data['nicname'] ? $data['nicname'] : '' ;

        }

        $data['create_ip'] = get_client_ip();

        $data['is_edit'] = 2;

        $data['create_time'] = NOW_TIME;

        //生成邀请码
        $data['invitation'] = create_randomstr(8);

        //检测邀请码是否已存在
        if (self::$model->where(['invitation' => $data['invitation']])->find())
            $data['invitation'] = create_randomstr(8);

        $data['uuid'] = md5(md5($data['create_time']) . $data['invitation']);

        if ($uid = self::$model->add($data)) {

            $thirds['open_id'] = $data['open_id'];
            $thirds['source_type'] = $data['source_type'];
            $thirds['created'] = NOW_TIME;
            $thirds['uid'] = $uid;

            $thirdLogic = D('Common/ThirdAuth', 'Logic');

            //存入第三方
            $result = $thirdLogic::create($thirds);
            if ($result['code'] == 200) {

                //如果有邀请码则梳理子父级关系
                if ($invitation)
                    self::invitation($invitation, $uid);

                //返回用户数据
                $userinfo = self::$model
                    ->where(['uid' => $uid])
                    ->field('uuid,username,nicname,mobile,avatar,create_time,autograph,invitation')
                    ->find();

                $userinfo['create_time'] = date('Y-m-d H:i:s',$userinfo['create_time']);


                return ['code' => 200, 'msg' => '注册成功', 'data' => $userinfo];

            }

            self::$model->where(['uid' => $uid])->delete();

            return ['code' => 300, 'msg' => '注册失败'];

        }

        return ['code' => 300, 'msg' => '注册失败!'];

    }

    /**
     * @introduction: 创建用户时梳理子父级关系
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $mobile 手机号码
     * @return array
     */
    private function invitation($invitation, $uid)
    {

        //获取邀请码用户
        $parent1 = self::$model
            ->where(['invitation' => $invitation])
            ->find();


        //更新第一级父级的数据
        if ($parent1) {

            $parent1_uid = $parent1['uid'];

            self::$model
                ->where(['uid' => $parent1['uid']])
                ->save(['first_child' => trim($parent1['first_child'] . ',' . $uid, ',')]);

            //获取第二级父级数据
            if ($parent1['first_parent']) {
                $parent2 = self::$model
                    ->where(['uid' => $parent1['first_parent']])
                    ->find();
            }

            //更新第二级父级的数据
            if ($parent2) {

                $parent2_uid = $parent2['uid'];

                self::$model
                    ->where(['uid' => $parent2['uid']])
                    ->save(['second_child' => trim($parent2['second_child'] . ',' . $uid, ',')]);

                //获取第二级父级数据
                if ($parent2['first_parent']) {
                    $parent3 = self::$model
                        ->where(['uid' => $parent2['first_parent']])
                        ->find();
                }


                //更新第三级父级的数据
                if ($parent3) {

                    $parent3_uid = $parent3['uid'];

                    self::$model
                        ->where(['uid' => $parent3['uid']])
                        ->save(['third_child' => trim($parent3['third_child'] . ',' . $uid, ',')]);

                }
            }

        }

        //更新当前会员父级数据
        if ($parent1_uid)
            $parents['first_parent'] = $parent1_uid;

        if ($parent2_uid)
            $parents['second_parent'] = $parent2_uid;

        if ($parent3_uid)
            $parents['third_parent'] = $parent3_uid;

        self::$model->where(['uid' => $uid])->save($parents);

        return true;

    }

    /**
     * @introduction: 检测手机号码
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $mobile 手机号码
     * @return array
     */
    static public function checkMobile($mobile)
    {

        if (!preg_match("/^1[3|4|5|6|7|8]\d{9}$/", $mobile))
            return ['code' => 300, 'msg' => '手机号码格式错误!'];

        if (self::$model->where(['mobile' => $mobile])->find())
            return ['code' => 300, 'msg' => '手机号码已存在!'];

        return true;

    }

    /**
     * @introduction: 检测服务端手机号码
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $mobile 手机号码
     * @return array
     */
    static public function checkAppMobile($mobile)
    {

        if (!preg_match("/^1[3|4|5|6|7|8]\d{9}$/", $mobile))
            return ['code' => 100, 'msg' => '手机号码格式错误!'];

        if (self::$model->where(['mobile' => $mobile])->find())
            return ['code' => 200];

        return ['code' => 300, 'msg' => '手机号码不存在!'];

    }

    /**
     * @introduction: 检测用户名
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 需要插入的数据
     * @return array
     */
    static public function checkUsername($username)
    {

        if (!preg_match("/^[a-zA-Z0-9-_]{6,20}$/", $username))
            return ['code' => 300, 'msg' => '用户名格式错误!'];

        if (self::$model->where(['username' => $username])->find())
            return ['code' => 300, 'msg' => '用户名已存在!'];

        return true;

    }

    /**
     * @introduction: 会员登录
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 登录所需的参数
     * @return array
     */
    static public function login($data)
    {

        //获取第三方登录open_id
        $open_id = $data['open_id'];
        //获取第三方登录类型
        $source_type = $data['source_type'];

        if ($open_id && $source_type) {

            $thirdLogic = D('Common/ThirdAuth', 'Logic');

            $result = $thirdLogic::getOneMemberData($open_id, $source_type);

            if ($result['code'] == 200) {

                session('uid', $result['data']['uid']);
                //登录成功更新数据
                $passinfo = password($result['data']['password']);

                $loginInfo['login_total'] = $result['data']['login_total'] + 1;

                self::$model
                    ->where(['uid' => $result['data']['uid']])
                    ->save($loginInfo);

            }

            return $result;
        } else {

            if (!$data['sign'])
                return ['code' => 300, 'msg' => '用户名或手机号码不能为空!'];

            if (!$data['password'])
                return ['code' => 300, 'msg' => '密码不能为空!'];

            $where = self::getSignType($data['sign']);

            $userinfo = self::$model
                ->where($where)
                ->find();

            if (!$userinfo)
                return ['code' => 300, 'msg' => '用户不存在!'];

            if (password($data['password'], $userinfo['encrypt']) != $userinfo['password'])
                return ['code' => 300, 'msg' => '密码错误!'];

            //登录成功更新数据
            $passinfo = password($data['password']);

            $loginInfo['login_total'] = $userinfo['login_total'] + 1;
            $loginInfo['password'] = $passinfo['password'];
            $loginInfo['encrypt'] = $passinfo['encrypt'];

            self::$model
                ->where(['uid' => $userinfo['uid']])
                ->save($loginInfo);
            //记录session

            session('uid', $userinfo['uid']);

            $userinfo['create_time'] = date('Y-m-d H:i:s',$userinfo['create_time']);
            return ['code' => 200, 'msg' => '登录成功!', 'data' => $userinfo];

        }


    }

    /**
     * @introduction: 检测用户输入的是手机号码还是用户名
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 登录所需的参数
     * @return array
     */
    static function getSignType($sign)
    {
        if (!$sign) return false;
        $return = [];
        $regxSign = [
            'mobile' => "/^1[3|4|5|6|7|8]\d{9}$/",
            'username' => "/^[a-zA-Z0-9-_]+$/",
        ];
        foreach ($regxSign as $k => $v) {
            if (preg_match($v, $sign)) {
                $return[$k] = strtolower($sign);
                break;
            }
        }
        return $return;
    }

    /**
     * @introduction: 分析会员基础信息
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 登录所需的参数
     * @return array
     */
    public function update($data, $uid)
    {

        if (!intval($uid))
            return ['code' => 500, 'msg' => '请登录!'];

        if (!self::$model->where(['uid' => $uid])->count())
            return ['code' => 300, 'msg' => '用户不存在!'];

        //检测是否有username,如果有检测当前用户是否可以修改username
        if ($data['username']) {

            $is_edit = self::$model->where(['uid' => $uid])->getField('is_edit');

            if ($is_edit != 2)
                return ['code' => 300, 'msg' => '您不能修改用户名!'];

        }

        $result = self::$model->where(['uid' => $uid])->save($data);

        if ($result !== false) {

            $userinfo = self::$model
                ->where(['uid' => $uid])
                ->find();

            $userinfo['create_time'] = date('Y-m-d H:i:s',$userinfo['create_time']);

            return ['code' => 200, 'msg' => '更新成功!', 'data' => $userinfo];

        }

        return ['code' => 300, 'msg' => '更新失败!'];

    }

    /**
     * @introduction: 修改密码
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $data 登录所需的参数
     * @return array
     */
    static public function updatePassword($data, $uid)
    {

        if (!intval($uid))
            return ['code' => 500, 'msg' => '请登录!'];

        if (!$data['password'])
            return ['code' => 300, 'msg' => '新密码不能为空!'];

        if (!preg_match("/^[0-9A-Za-z]{5,}$/", $data['password']))
            return ['code' => 300, 'msg' => '密码格式不对!'];

        if (!$data['old_password'])
            return ['code' => 300, 'msg' => '旧密码不能为空!'];

        $userinfo = self::$model
            ->where(['uid' => $uid])
            ->field('password,encrypt')
            ->find();

        if (password($data['old_password'], $userinfo['encrypt']) != $userinfo['password'])
            return ['code' => 300, 'msg' => '旧密码错误'];

        $passinfo = password($data['password']);

        if (self::$model->where(['uid' => $uid])->save($passinfo))
            return ['code' => 200, 'msg' => '修改成功!'];

        return ['code' => 300, 'msg' => '修改失败'];


    }
    /**
     * Introduction: 找回密码
     * @author: 杨陈鹏
     * @email: wanglong@cdlinglu.com
     */
    /*

        {
            mobile: '13123144999',
            mobile_code: '3432',
            password: 'asdffasd',

        }


     */
    public function findPassword($data)
    {

        $check_info = self::checkAppMobile($data['mobile']);

        if (!preg_match("/^[0-9A-Za-z]{5,}$/", $data['password']))
            return ['code' => 300, 'msg' => '密码格式不对!'];

        if ($check_info['code'] == 300 || $check_info['code'] == 100) {

            $check_info['code'] = 300;

            return $check_info;

        }


        $mobile_code = session('mobile_code_' . $data['mobile']);

        //超级验证码  微信用   临时
        //if ($data['mobile_code'] != 9999) {
            if ($data['mobile_code'] != $mobile_code)
                return ['code' => 300, 'msg' => '验证码错误'];
        //}

        $passinfo = password($data['password']);

        if (self::$model->where(['mobile' => $data['mobile']])->save($passinfo))
            return ['code' => 200, 'msg' => '密码修改成功!'];

        return ['code' => 300, 'msg' => '密码修改失败!'];

    }


    /**
     * Introduction: 申请微分销
     * @author: 杨陈鹏
     * @email: wanglong@cdlinglu.com
     */
    public function applyDis($data)
    {

        if(!$data['uid'])
            return ['code' => 300,'msg' => '缺少用户信息!'];

        if(!$data['name'])
            return ['code' => 300,'msg' => '请输入真实名称!'];

        if(!$data['mobile'])
            return ['code' => 300,'msg' => '请输入电话号码!'];

        if(!$data['id_card'])
            return ['code' => 300,'msg' => '请输入身份证号码!'];

        if(!$data['alipay_account'])
            return ['code' => 300,'msg' => '请输入支付宝帐号!'];


        $data['create_time'] = NOW_TIME;

        $data['status']      = 1;

        if(self::$apply_dis->where(['uid' => $data['uid']])->count())
        {

            $uid = $data['uid'];
            unset($data['uid']);

            $result = self::$apply_dis->where(['uid' => $uid])->save($data);

            if($result !== false){

                $member_logic = D('Common/Member','Logic');

                $member_logic::$model->where(['uid' => $data['uid']])->setField('micro_distribution',2);

                return ['code' => 200, 'msg' => '申请成功,请等待客服处理!'];
            }


        }else {



            if(self::$apply_dis->add($data)){

                $member_logic = D('Common/Member','Logic');

                $member_logic::$model->where(['uid' => $data['uid']])->setField('micro_distribution',2);

                return ['code' => 200, 'msg' => '申请成功,请等待客服处理!'];
            }

        }

        return ['code' => 300, 'msg' => '申请失败'];

    }

    /**
     * Introduction: 获取微分销列表
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function distributionList($where,$page,$nums,$field = '*')
    {

        $total = self::$apply_dis
                    ->where($where)
                    ->count();

        $data = self::$apply_dis
                    ->where($where)
                    ->field($field)
                    ->page($page,$nums)
                    ->order('create_time  desc')
                    ->select();

        return ['code' => 200, 'data' =>$data,'total' =>$total];


    }

    /**
     * Introduction: 获取一条微分销申请记录
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function distributionOne($uid)
    {

        $data = self::$apply_dis->where(['uid' => $uid])->find();

        return ['code' => 200 ,'data' => $data];

    }

}